package com.dayaokeji.rhythmschoolstudent.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;

import com.dayaokeji.rhythmschoolstudent.client.common.base.App;
import com.dayaokeji.rhythmschoolstudent.wiget.PermissionTipsDialog;
import com.orhanobut.logger.Logger;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RequestExecutor;
import com.yanzhenjie.permission.Setting;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Function;

// Created by Zeno on 2018/5/22
// version 1.0
// Copyright (C) 2018 -- 2020 ALL Right
public class PermissionUtil {

    @SuppressLint("CheckResult")
    public static Observable<PermissionResult> checkPermission(final @NonNull Activity activity, @NonNull final Build build) {
        return Observable.create(new ObservableOnSubscribe<PermissionResult>() {
            @Override
            public void subscribe(final ObservableEmitter<PermissionResult> emitter) throws Exception {
                AndPermission.with(activity)
                        .runtime()
                        .permission(build.getPermissions())
                        .onGranted(new Action<List<String>>() {
                            @Override
                            public void onAction(List<String> data) {
                                final PermissionResult permissionResult = new PermissionResult(build.permissions,true);
                                emitter.onNext(permissionResult);
                            }
                        })
                        .onDenied(new Action<List<String>>() {
                            @Override
                            public void onAction(final List<String> data) {
                                // 这些权限被用户总是拒绝。
                                if (AndPermission.hasAlwaysDeniedPermission(activity, build.permissions)) {
                                    PermissionTipsDialog permissionTipsDialog = PermissionTipsDialog.Companion.newInstance(build.permissions);
                                    permissionTipsDialog.setSettingClickListener(new PermissionTipsDialog.SettingClickListener() {
                                        @Override
                                        public void setting() {
                                            AndPermission.with(activity)
                                                    .runtime()
                                                    .setting()
                                                    .onComeback(new Setting.Action() {
                                                        @Override
                                                        public void onAction() {
                                                            if (AndPermission.hasPermissions(activity, build.permissions)) {
                                                                final PermissionResult permissionResult = new PermissionResult(build.permissions, true);
                                                                emitter.onNext(permissionResult);
                                                            } else {
                                                                final PermissionResult permissionResult = new PermissionResult(build.permissions, false);
                                                                emitter.onNext(permissionResult);
                                                            }
                                                        }
                                                    }).start();
                                        }
                                    });
                                    try{
                                        if (activity instanceof AppCompatActivity) {
                                            AppCompatActivity compatActivity = (AppCompatActivity) activity;
                                            permissionTipsDialog.show(compatActivity.getSupportFragmentManager(), "permission");
                                        }
                                    }catch (Exception e) {
                                        e.printStackTrace();
                                        Logger.e("Activity cast AppCompactActivity exception");
                                    }

                                }
                            }
                        })
                        .rationale(new Rationale<List<String>>() {
                            @Override
                            public void showRationale(final Context context, final List<String> data, final RequestExecutor executor) {
                                DialogUtils.showPermissionDenyDialog(activity, build.getTips(), executor);
                            }
                        })
                       .start();
            }
        });
    }

    /**
     * 存储权限
     * @param activity
     * @return
     */
    public static Observable<Boolean> checkStorePermission(Activity activity) {
        final Build build = new Build();
        build.setPermissions(Permission.Group.STORAGE);
        build.setTips("请允许我们访问存储权限，方便您下载和上传文件");
        return checkPermission(activity, build).map(new Function<PermissionResult, Boolean>() {
            @Override
            public Boolean apply(PermissionResult permissionResult) throws Exception {
                if (permissionResult.isHasAccess()) {
                    return true;
                }else{
                    return false;
                }
            }
        });
    }

    /**
     * 存储权限
     * @param activity
     * @return
     */
    public static Observable<Boolean> checkStorePermission(Activity activity,String tips) {
        final Build build = new Build();
        build.setPermissions(Permission.Group.STORAGE);
        build.setTips(tips);
        return checkPermission(activity, build).map(new Function<PermissionResult, Boolean>() {
            @Override
            public Boolean apply(PermissionResult permissionResult) throws Exception {
                if (permissionResult.isHasAccess()) {
                    return true;
                }else{
                    return false;
                }
            }
        });
    }

    public static Observable<Boolean> checkCameraPermission(Activity activity) {
        final Build build = new Build();
        build.setPermissions(PermissionGroup.CAMERA_AND_STORE);
        build.setTips("您当前操作需要拍照权限，请允许我们访问拍照权限");
        return checkPermission(activity, build).map(new Function<PermissionResult, Boolean>() {
            @Override
            public Boolean apply(PermissionResult permissionResult) throws Exception {
                if (permissionResult.isHasAccess()) {
                    return true;
                }else{
                    return false;
                }
            }
        });
    }

    public static void startSetting(Activity activity) {
        AndPermission.with(activity)
                .runtime()
                .setting()
                .start();
    }

    public static boolean hasPermission(String[] permissions) {
        return AndPermission.hasPermissions(App.getAppContext(),permissions);
    }

    public static boolean hasPermissions(String ...permission) {
        return AndPermission.hasPermissions(App.getAppContext(),permission);
    }

    public static String getPermissionName(Context context, String[] args) {
        List<String> strings = Permission.transformText(context, args);
        StringBuilder builder = new StringBuilder();
        for (String permissionName : strings) {
            builder.append("【");
            builder.append(permissionName);
            builder.append("】");
            builder.append(" ");
        }
        return builder.toString();
    }

    public static class Build{
        private String[] permissions;
        private String tips;

        public Build setPermissions(String[] permissions) {
            this.permissions = permissions;
            return this;
        }

        public Build setTips(String tips) {
            this.tips = tips;
            return this;
        }

        public String[] getPermissions() {
            return permissions;
        }

        public String getTips() {
            return tips;
        }
    }

    public static class PermissionResult{
        private String[] permissions;
        private boolean hasAccess;

        public PermissionResult(String[] permissions, boolean hasAccess) {
            this.permissions = permissions;
            this.hasAccess = hasAccess;
        }

        public String[] getPermissions() {
            return permissions;
        }

        public void setPermissions(String[] permissions) {
            this.permissions = permissions;
        }

        public boolean isHasAccess() {
            return hasAccess;
        }

        public void setHasAccess(boolean hasAccess) {
            this.hasAccess = hasAccess;
        }
    }
}
